/**
 * 请求模块，依赖于login模块，目前基于axios实现，封装axios
 */

import axios from 'axios';
import login from '../login';
import errorMap from '../errorMap';

const requestInstance = axios.create({
    //默认10秒超时
    timeout: 1000,
});

//通过设置拦截器，实现校验登录的目的
requestInstance.interceptors.request.use((reqConfig = {hasToken: false})=>{
    return Promise.resolve()
        .then(()=>{
            //如果需要登录，就将token信息放到url上面
            if(reqConfig.hasToken === true){
                //如果登录了直接放到url上面
                if(login.isLoggedIn()){
                    var accessToken = login.getToken();
                    //将token放到url里面去
                    reqConfig.url = ~reqConfig.url.indexOf('?') ? reqConfig.url + "&token=" + accessToken : reqConfig.url + "?token=" + accessToken
                    return reqConfig;
                } else {
                    //未登录抛出异常
                    throw new Error(errorMap.UNLOGIN_ERROR)
                }
            } else {
                return reqConfig;
            }
        })
}, function (err) {
    return Promise.reject(err);
});

//通过拦截器将异常封装
requestInstance.interceptors.response.use(({data})=> {
    //处理正确响应逻辑
    if (data.state + '' != '0') {
        //如果state不为0，表示出现业务异常
        const error = new Error(errorMap.BUSINESS_ERROR)
        error.data = data
        throw error
    } else {
        //否则将数据返回
        return typeof data === 'object' ? data.data : data;
    }
}, (error)=>{
    if (error && error.config && error.hasOwnProperty("response")) {
        if (error.response) {
            switch (error.response.status) {
                case "":
                case 0:
                case 502:
                    error = new Error(errorMap.NETWORK_ERROR);
                    break;
                default:
                    //对如500、404等那种通用的错误
                    error = errorMap.BUSINESS_ERROR;
                    error.data = {state: '-1'}
            }
        } else {
            error = new Error(errorMap.NETWORK_ERROR);
        }
    }
    throw error;
})

const request = {
    get: (url, reqConfig={}) => {
        return requestInstance.get(url, reqConfig)
    },
    post: (url, data={}, reqConfig={}) => {
        //设置content-type
        let headers = { "content-type": "application/json;charset=UTF-8"};
        reqConfig.headers = Object.assign(headers, reqConfig.headers || {});

        return requestInstance.post(url, data, reqConfig)
    },
    put: (url, data={}, reqConfig={}) => {
        //设置content-type
        let headers = { "content-type": "application/json;charset=UTF-8"};
        reqConfig.headers = Object.assign(headers, reqConfig.headers || {});

        return requestInstance.put(url, data, reqConfig)
    },
    delete: (url, reqConfig={}) => {
        return requestInstance.delete(url, reqConfig)
    }
}

export default request;
